import React from 'react';
import './../../form.less';

import moment from 'moment';
import {Button, Icon, message, Row} from 'antd';
import BreadcrumbCustom from "../../../common/BreadcrumbCustom";
import TutorTable from "./TutorTable";
import TutorCreateForm from "./TutorForm";
import BraftEditor from 'braft-editor'

export default class Tutor extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            pageSize: 5,
            total: 0,
            current: 1,
            userType: 3,
            visible: false, //新建窗口隐藏
            dataSource: [], //所有信息
            userSource:[], //用户信息展示
            selectedRowKeys: [],
            isUpdate: false,
            loading: true
        };
    }

    //搜索条件
    onChangeLinkUrl = (e) => {
        const value = e.target.value;
        this.setState({
            linkUrl: value,
        })
    };

    pageSizeChange = (current, pageSize) => {
        this.setState({
            pageSize: pageSize,
            current: current
        },() => this.getData())
    }

    getData = () => {
        var url = '/manage/tutor/query'
        const searchCondiction = new Object()
        searchCondiction.pageSize = this.state.pageSize;
        searchCondiction.pageNumber = this.state.current;
        const conditionList = [];
        searchCondiction.conditionList = conditionList;
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(searchCondiction)
        }).then((response) => {
            return response.json()
        }).then((res) => {
            console.log(res)
            if (res.code == 200) {
                let results = res.result.list
                let userSource = []
                results.map(item =>{
                    userSource.push(item.tUser)
                })
                this.setState({
                    datasource: res.result.list,
                    userSource: userSource,
                    total:res.result.total,
                    loading: false
                });
            }
            this.form.resetFields()
        })
    }

    //渲染
    componentDidMount() {
        this.getData();
    }

    //搜索按钮
    btnSearch_Click = () => {
        this.getData();
    };
    //重置按钮
    btnClear_Click = () => {
        this.setState({
            linkUrl: ''
        });
    };
    
    //新建信息弹窗
    CreateItem = () => {
        this.setState({
            visible: true,
            isUpdate: false,
        });
        const form = this.form;
        form.resetFields();
    };

    //单个删除
    onDelete = (tutorId) => {
        var url = '/manage/tutor/delete/' + tutorId;
        fetch(url, {
            method: 'DELETE'
        }).then((response) => {
            return response.json()
        }).then((res) => {
            if (res.code == 200) {
                message.success("操作成功")
                this.getData();
            } else {
                message.success("操作失败")
            }
        })
    };

    //新增
    handleCreate = () => {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log('Received values of form: ', values);
            //富文本编辑器内容转换
            values.descrition_NotFileter = values.descrition_NotFileter.toHTML()
            values.createtime = moment().format("YYYY-MM-DD hh:mm:ss");
            var url = `/manage/tutor/save`
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(values)
            }).then((response) => {
                return response.json()
            }).then((res) => {
                if (res.code === 200) {
                    message.success("操作成功")
                    this.getData();
                } else {
                    message.success("操作失败")
                    //window.location.reload() 
                }
            })
            form.resetFields()
            //let formClear = setTimeout(form.resetFields,2000);
            this.setState({
                visible: false,
            })
           
        });
    };

    // componentWillUnmount(){
    //     clearTimeout(formClear)
    // };


    //更新修改
    handleUpdate = () => {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            //富文本编辑器内容转换
            values.descrition_NotFileter = values.descrition_NotFileter.toHTML()
            values.createtime = moment().format("YYYY-MM-DD hh:mm:ss");

            console.log("8888888",values)
            var url = 'manage/tutor/update'
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(values)
            }).then((response) => {
                return response.json()
            }).then((res) => {
                if (res.code == 200) {
                    message.success("操作成功")
                    this.getData();
                } else {
                    message.success("操作失败")
                    //window.location.reload()
                }
            })
            form.resetFields();
            this.setState({
                visible: false,
            });
        });
    };
    //取消
    handleCancel = () => {
        this.setState({visible: false});
    };
    //批量删除
    MinusClick = () => {
        this.state.selectedRowKeys.forEach(index => {
            this.onDelete(this.state.datasource[index].id)
        })
    };
    //点击修改
    editClick = (key) => {
        const tutors = this.state.datasource.filter( tutor => tutor.tUser.id == key)[0];
        console.log('tutors',tutors)
        const form = this.form;
        form.setFieldsValue({
            id: tutors.tUser.id,
            fullName: tutors.tUser.fullName,
            avatarUrl: tutors.tUser.avatarUrl,
            phoneNum: tutors.tUser.phoneNum,
            openid: tutors.tUser.openid,
            isTj: tutors.isTj,
            isFx: tutors.isFx,
            fxOrdNum: tutors.fxOrdNum,
            tjOrdNum: tutors.tjOrdNum,
            isFastAsk: tutors.isFastAsk,
            fastAskPrice: tutors.fastAskPrice,
            location: tutors.location,
            topic: tutors.topic,
            label: tutors.label,
            categorys: tutors.categorys,
            descrition_NotFileter: BraftEditor.createEditorState(tutors.descrition_NotFileter),
            consultPrice: tutors.consultPrice,
            preferentialPrice: tutors.preferentialPrice,
        });
        this.setState({
            visible: true,
            isUpdate: true
        });
    };
    //单选框改变选择
    checkChange = (selectedRowKeys) => {
        this.setState({selectedRowKeys: selectedRowKeys});
    };

    render() {
        const questiontxt = () => {
            return (
                <p><Icon type="plus-circle-o"/> : 新建信息</p>
            )
        };
        return (
            <div>
                <BreadcrumbCustom paths={['首页', '导师管理']}/>
                <div className='formBody'>
                    {/* <Row gutter={16}>*/}
                        {/*<Col className="gutter-row" sm={8}>*/}
                            {/*<Input*/}
                                {/*placeholder="跳转地址"*/}
                                {/*value={this.state.linkUrl}*/}
                                {/*onChange={this.onChangeLinkUrl}*/}
                            {/*/>*/}
                        {/*</Col>*/}
                    {/*</Row> */}
                    <Row gutter={16}>
                        <div className='plus' onClick={this.CreateItem}>
                            <Icon type="plus-circle"/>
                        </div>
                        <div className='btnOpera'>
                            <Button type="primary" onClick={this.btnSearch_Click}
                                    style={{marginRight: '10px'}}>查询</Button>
                            <Button type="primary" onClick={this.btnClear_Click}
                                    style={{background: '#f8f8f8', color: '#108ee9'}}>重置</Button>
                        </div>
                    </Row>
                    <TutorTable
                        dataSource={this.state.userSource}
                        checkChange={this.checkChange}
                        onDelete={this.onDelete}
                        editClick={this.editClick}
                        loading={this.loading}
                        pageSizeChange={this.pageSizeChange}
                        total={this.state.total}
                        pageSize={this.state.pageSize}
                        current={this.state.current}
                    />
                    {this.state.isUpdate ?
                        <TutorCreateForm ref={(form) => this.form = form} visible={this.state.visible}
                                          onCancel={this.handleCancel} onCreate={this.handleUpdate} title="修改类目"
                                          okText="更新" />
                        : <TutorCreateForm ref={(form) => this.form = form} visible={this.state.visible}
                                            onCancel={this.handleCancel} onCreate={this.handleCreate} title="新建导师"
                                            okText="保存"/>}
                </div>
            </div>
        )
    }
}